package roles;

import avenue.MyWindowEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.List;
import javax.persistence.EntityManager;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import model.DBManager;
import model.Module;
import model.UserRole;

import model.RolePermission;
import org.jdesktop.beansbinding.AutoBinding;
import org.jdesktop.swingbinding.*;
import org.jdesktop.swingbinding.JTableBinding.ColumnBinding;
import users.*;

public class ListRolesForm extends javax.swing.JFrame
{

    EntityManager em;
    JFrame thisFrame;
    int s;
    UserRole ur;
    RolePermission rp, rp1, rp2, rp3, rp4, rp5, rp6;
    Module m1, m2, m3, m4, m5, m6;
    boolean miOrismenaDiakeomataGiaPalioXrisit;

    /**
     * Creates new form ListUsersForm
     */
    public ListRolesForm()
    {
        em = DBManager.em;
        if (!em.getTransaction().isActive())
          {
            em.getTransaction().begin();
          }
        initComponents();
    }

    public void createSixModules()
    {
        m1 = em.createNamedQuery("Module.findById",
                Module.class)
                .setParameter("id", 1).getSingleResult();
        m2 = em.createNamedQuery("Module.findById",
                Module.class)
                .setParameter("id", 2).getSingleResult();
        m3 = em.createNamedQuery("Module.findById",
                Module.class)
                .setParameter("id", 3).getSingleResult();
        m4 = em.createNamedQuery("Module.findById",
                Module.class)
                .setParameter("id", 4).getSingleResult();
        m5 = em.createNamedQuery("Module.findById",
                Module.class)
                .setParameter("id", 5).getSingleResult();
        m6 = em.createNamedQuery("Module.findById",
                Module.class)
                .setParameter("id", 6).getSingleResult();

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents()
    {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        selectUserRolesQuery = java.beans.Beans.isDesignTime() ? null : em.createQuery("select ur from  UserRole ur");
        userRolesList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(selectUserRolesQuery.getResultList());
        selectPermsByUserRoleQUERY = em.createQuery("select rp from RolePermission rp where rp.roleId=:userRole").setParameter("userRole",ur);
        selectPerrmsByUserRoleLIST = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(selectPermsByUserRoleQUERY.getResultList());
        editRoleButton = new javax.swing.JButton();
        deleteRoleButton = new javax.swing.JButton();
        newRoleButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        roleTable = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        saveButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        statusLabel = new javax.swing.JLabel();
        jSeparator2 = new javax.swing.JSeparator();
        saveAndBackButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        editRoleButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/edit1.png"))); // NOI18N
        editRoleButton.setText("Επεξεργασία");
        editRoleButton.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                editRoleButtonActionPerformed(evt);
            }
        });

        deleteRoleButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/remove.gif"))); // NOI18N
        deleteRoleButton.setText("Διαγραφή");
        deleteRoleButton.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                deleteRoleButtonActionPerformed(evt);
            }
        });

        newRoleButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/add.gif"))); // NOI18N
        newRoleButton.setText("Νέος");
        newRoleButton.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                newRoleButtonActionPerformed(evt);
            }
        });

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, userRolesList, roleTable);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${roleName}"));
        columnBinding.setColumnName("Role Name");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        jScrollPane1.setViewportView(roleTable);
        roleTable.getColumnModel().getColumn(0).setResizable(false);

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 20)); // NOI18N
        jLabel1.setText("Πίνακας Ρόλων");

        saveButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/save.gif"))); // NOI18N
        saveButton.setText("Αποθήκευση");
        saveButton.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                saveButtonActionPerformed(evt);
            }
        });

        cancelButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/cancel.gif"))); // NOI18N
        cancelButton.setText("Άκυρο");
        cancelButton.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                cancelButtonActionPerformed(evt);
            }
        });

        statusLabel.setText("ΚΑΜΙΑ ΑΛΛΑΓΗ");

        saveAndBackButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/save.gif"))); // NOI18N
        saveAndBackButton.setText("Αποθήκευση Αλλαγών και Επιστροφή");
        saveAndBackButton.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                saveAndBackButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSeparator1)
                    .addComponent(jSeparator2)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(newRoleButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(deleteRoleButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(editRoleButton)))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(saveButton)
                        .addGap(18, 18, 18)
                        .addComponent(saveAndBackButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cancelButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 57, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(statusLabel)
                .addGap(24, 24, 24))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(1, 1, 1)
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(7, 7, 7)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 238, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(newRoleButton)
                    .addComponent(deleteRoleButton)
                    .addComponent(editRoleButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(statusLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 31, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(saveAndBackButton)
                    .addComponent(saveButton)
                    .addComponent(cancelButton))
                .addContainerGap())
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void newRoleButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newRoleButtonActionPerformed
        // TODO add your handling code here:
        ur = new UserRole();
        em.persist(ur);

        rp = new RolePermission();//////22
        ////////////////////////////////////
        createSixModules();
        rp1 = new RolePermission();
        rp1.setModuleId(m1);
        rp2 = new RolePermission();
        rp2.setModuleId(m2);
        rp3 = new RolePermission();
        rp3.setModuleId(m3);
        rp4 = new RolePermission();
        rp4.setModuleId(m4);
        rp5 = new RolePermission();
        rp5.setModuleId(m5);
        rp6 = new RolePermission();
        rp6.setModuleId(m6);


        ///////////////////////////////////

        //EditRoleForm2 erf = new EditRoleForm2(ur, rp, false, false);
        EditRoleForm3 erf = new EditRoleForm3(ur, rp1, rp2, rp3, rp4, rp5, rp6, false, false);
        erf.setVisible(true);
        thisFrame = this;
        thisFrame.setEnabled(false);
        //************
        erf.addWindowListener(new WindowListener()
        {
            public void windowClosed(WindowEvent arg0)
            {
                System.out.println("Window close event occur");
                if (((MyWindowEvent) arg0).exitAndSave)
                  {
                    System.out.println("event save before closing");
                    userRolesList.add(ur);
                    int row = userRolesList.size() - 1;
                    ///////////////////
                    em.persist(rp1);
                    em.persist(rp2);
                    em.persist(rp3);
                    em.persist(rp4);
                    em.persist(rp5);
                    em.persist(rp6);
                    selectPerrmsByUserRoleLIST.add(rp1);
                    selectPerrmsByUserRoleLIST.add(rp2);
                    selectPerrmsByUserRoleLIST.add(rp3);
                    selectPerrmsByUserRoleLIST.add(rp4);
                    selectPerrmsByUserRoleLIST.add(rp5);
                    selectPerrmsByUserRoleLIST.add(rp6);
                    //System.out.print(rp);
                    /////////////

                    roleTable.setRowSelectionInterval(row, row);
                    roleTable.scrollRectToVisible(roleTable.getCellRect(row, 0, true));
                    thisFrame.setEnabled(true);

                  }
                else
                  {
                    System.out.println("cancel all changes before before closing");
                    thisFrame.setEnabled(true);
                    if (em.getTransaction().isActive())
                      {
                        em.getTransaction().rollback();//original
                        statusLabel.setText("Δεν υπάρχουν Αλλαγές");
                      }
                    em.getTransaction().begin();

                    java.util.Collection data = selectUserRolesQuery.getResultList();
                    for (Object entity : data)
                      {
                        em.refresh(entity);
                      }
                    userRolesList.clear();
                    userRolesList.addAll(data);
                  }
            }

            public void windowActivated(WindowEvent arg0)
            {
                System.out.println("Window Activated");
            }

            public void windowClosing(WindowEvent arg0)
            {
                System.out.println("Window Closing");
            }

            public void windowDeactivated(WindowEvent arg0)
            {
                System.out.println("Window Deactivated");
            }

            public void windowDeiconified(WindowEvent arg0)
            {
                System.out.println("Window Deiconified");
            }

            public void windowIconified(WindowEvent arg0)
            {
                System.out.println("Window Iconified");
            }

            public void windowOpened(WindowEvent arg0)
            {
                System.out.println("Window Opened");
            }
        });
    }//GEN-LAST:event_newRoleButtonActionPerformed

    public List<RolePermission> retrieveRolePermisionByUserRole(UserRole user_role)
    {
        String idS = user_role.getId().toString();
        String strSQL = "select * from ROLE_PERMISSION where ROLE_PERMISSION.ROLE_ID = " + idS;

        List<RolePermission> urList = em.createNativeQuery(strSQL,
                RolePermission.class).getResultList();
        return urList;
    }

    public void deleteRolePermissionByUserRole(UserRole user_role)
    {
        RolePermission rTemp = retrieveRolePermisionByUserRole(user_role).get(0);
        em.remove(rTemp);
        em.getTransaction().commit();
    }

    public void deleteUserRole(UserRole user_role)
    {
        if (!em.getTransaction().isActive())
          {
            em.getTransaction().begin();
          }
        UserRole ur2 =
                em.createNamedQuery("UserRole.findById",
                UserRole.class)
                .setParameter("id", user_role.getId()).getSingleResult();

        em.remove(ur2);
        em.getTransaction().commit();

    }

    private void deleteRoleButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteRoleButtonActionPerformed
        // TODO add your handling code here:
        if (!em.getTransaction().isActive())
          {
            em.getTransaction().begin();
          }
        int s = roleTable.getSelectedRow();
        if (s >= 0)
          {
            UserRole ur = userRolesList.get(roleTable.convertRowIndexToModel(s));
            // deleteRolePermissionByUserRole(ur);
            //  deleteUserRole(ur);
            userRolesList.remove(ur);
            em.remove(ur);
          }
    }//GEN-LAST:event_deleteRoleButtonActionPerformed

    private void editRoleButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editRoleButtonActionPerformed
        // TODO add your handling code here:
        //refershTable();
        s = roleTable.getSelectedRow();
        System.out.println(s);
        if (s >= 0)
          {
            ur = userRolesList.get(roleTable.getSelectedRow());
            em.persist(ur);

            List<RolePermission> tempL = retrieveRolePermisionByUserRole(ur);


            if (tempL.isEmpty())  // o xristis den exei sindethei me dikeomata
              {
//                System.out.print("den exoun rosthei dikeomanta gia ton xristi");
//                miOrismenaDiakeomataGiaPalioXrisit = true;

                createSixModules();
                rp1 = new RolePermission();
                rp1.setModuleId(m1);
                rp2 = new RolePermission();
                rp2.setModuleId(m2);
                rp3 = new RolePermission();
                rp3.setModuleId(m3);
                rp4 = new RolePermission();
                rp4.setModuleId(m4);
                rp5 = new RolePermission();
                rp5.setModuleId(m5);
                rp6 = new RolePermission();
                rp6.setModuleId(m6);

                EditRoleForm3 erf = new EditRoleForm3(ur, rp1, rp2, rp3, rp4, rp5, rp6, false, false);
                erf.setVisible(true);
                thisFrame = this;
                thisFrame.setEnabled(false);
                //************
                erf.addWindowListener(new WindowListener()
                {
                    public void windowClosed(WindowEvent arg0)
                    {
                        System.out.println("Window close event occur");
                        if (((MyWindowEvent) arg0).exitAndSave)
                          {
                            System.out.println("event save before closing");
                            userRolesList.add(ur);
                            int row = userRolesList.size() - 1;
                            ///////////////////
                            em.persist(rp1);
                            em.persist(rp2);
                            em.persist(rp3);
                            em.persist(rp4);
                            em.persist(rp5);
                            em.persist(rp6);
                            selectPerrmsByUserRoleLIST.add(rp1);
                            selectPerrmsByUserRoleLIST.add(rp2);
                            selectPerrmsByUserRoleLIST.add(rp3);
                            selectPerrmsByUserRoleLIST.add(rp4);
                            selectPerrmsByUserRoleLIST.add(rp5);
                            selectPerrmsByUserRoleLIST.add(rp6);
                            //System.out.print(rp);
                            /////////////

                            roleTable.setRowSelectionInterval(row, row);
                            roleTable.scrollRectToVisible(roleTable.getCellRect(row, 0, true));
                            refershTable();
                            thisFrame.setEnabled(true);

                          }
                        else
                          {
                            System.out.println("cancel all changes before before closing");
                            thisFrame.setEnabled(true);
                            if (em.getTransaction().isActive())
                              {
                                em.getTransaction().rollback();//original
                                statusLabel.setText("Δεν υπάρχουν Αλλαγές");
                              }
                            em.getTransaction().begin();

                            java.util.Collection data = selectUserRolesQuery.getResultList();
                            for (Object entity : data)
                              {
                                em.refresh(entity);
                              }
                            userRolesList.clear();
                            userRolesList.addAll(data);
                          }
                    }

                    public void windowActivated(WindowEvent arg0)
                    {
                        System.out.println("Window Activated");
                    }

                    public void windowClosing(WindowEvent arg0)
                    {
                        System.out.println("Window Closing");
                    }

                    public void windowDeactivated(WindowEvent arg0)
                    {
                        System.out.println("Window Deactivated");
                    }

                    public void windowDeiconified(WindowEvent arg0)
                    {
                        System.out.println("Window Deiconified");
                    }

                    public void windowIconified(WindowEvent arg0)
                    {
                        System.out.println("Window Iconified");
                    }

                    public void windowOpened(WindowEvent arg0)
                    {
                        System.out.println("Window Opened");
                    }
                });
              }
            else
              {
                miOrismenaDiakeomataGiaPalioXrisit = false;
                EditRoleForm3 erf = new EditRoleForm3(ur, false, true);

                erf.setVisible(true);
                thisFrame = this;
                thisFrame.setEnabled(false);
                //********************
                erf.addWindowListener(new WindowListener()
                {
                    public void windowClosed(WindowEvent arg0)
                    {
                        System.out.println("Window close event occur");
                        if (((MyWindowEvent) arg0).exitAndSave)
                          {
                            userRolesList.set(s, ur);
                            roleTable.setRowSelectionInterval(s, s);
                            roleTable.scrollRectToVisible(roleTable.getCellRect(s, 0, true));
                            roleTable.repaint();
                            thisFrame.setEnabled(true);
                          }
                        else
                          {
                            thisFrame.setEnabled(true);
                            if (em.getTransaction().isActive())
                              {
                                em.getTransaction().rollback();
                                statusLabel.setText("Δεν υπάρχουν Αλλαγές");
                              }
                            em.getTransaction().begin();
                            java.util.Collection data = selectUserRolesQuery.getResultList();
                            for (Object entity : data)
                              {
                                em.refresh(entity);
                              }
                            userRolesList.clear();
                            userRolesList.addAll(data);
                          }
                    }

                    public void windowActivated(WindowEvent arg0)
                    {
                        System.out.println("Window Activated");
                    }

                    public void windowClosing(WindowEvent arg0)
                    {
                        System.out.println("Window Closing");
                    }

                    public void windowDeactivated(WindowEvent arg0)
                    {
                        System.out.println("Window Deactivated");
                    }

                    public void windowDeiconified(WindowEvent arg0)
                    {
                        System.out.println("Window Deiconified");
                    }

                    public void windowIconified(WindowEvent arg0)
                    {
                        System.out.println("Window Iconified");
                    }

                    public void windowOpened(WindowEvent arg0)
                    {
                        System.out.println("Window Opened");
                    }
                });
              }




            //************

          }
    }//GEN-LAST:event_editRoleButtonActionPerformed

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_saveButtonActionPerformed
    {//GEN-HEADEREND:event_saveButtonActionPerformed
        // TODO add your handling code here:
        try
          {
            if (em.getTransaction().isActive())
              {
                em.getTransaction().commit();
                statusLabel.setText("Αλλαγές Αποθηκεύτηκαν");
              }

            if (!em.getTransaction().isActive())
              {
                em.getTransaction().begin();//original
                em.getTransaction().commit();
                statusLabel.setText("Αλλαγές Αποθηκεύτηκαν");
              }
            System.out.println("Record saved ");
          }
        catch (Exception ex)
          {
            String errorSTR = "Error \n";
            statusLabel.setText("Αλλαγές ΜΗ ΑΠΟΘΗΚΕΥΜΕΝΕΣ");
            if (ex.toString().contains("violation of foreign"))
              {
                errorSTR = errorSTR + "Foreign key Violation\n "
                        + "Ο εγγραφη είναι συνδεδεμενη με εγγραφή του πινακα"
                        + " ROLE_PERMISSION\n"
                        + "Ο ρόλος χρησιμοποιείται.";
              }

            JOptionPane.showMessageDialog(this, errorSTR, "Error", JOptionPane.ERROR_MESSAGE);

            userRolesList = org.jdesktop.observablecollections.ObservableCollections.observableList(selectUserRolesQuery.getResultList());
            refershTable();

          }
    }//GEN-LAST:event_saveButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_cancelButtonActionPerformed
    {//GEN-HEADEREND:event_cancelButtonActionPerformed
        MyWindowEvent we = new MyWindowEvent(this, WindowEvent.WINDOW_CLOSED, false);
        for (WindowListener l : this.getWindowListeners())
          {
            l.windowClosed(we);
          }
        this.setVisible(false);        // TODO add your handling code here:

    }//GEN-LAST:event_cancelButtonActionPerformed

    private void saveAndBackButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_saveAndBackButtonActionPerformed
    {//GEN-HEADEREND:event_saveAndBackButtonActionPerformed
        // TODO add your handling code here:
        try
          {
            if (em.getTransaction().isActive())
              {
                em.getTransaction().commit();
                statusLabel.setText("Αλλαγές Αποθηκεύτηκαν");
              }

            if (!em.getTransaction().isActive())
              {
                em.getTransaction().begin();//original
                em.getTransaction().commit();
                statusLabel.setText("Αλλαγές Αποθηκεύτηκαν");
              }
          }
        catch (Exception e)
          {
            JOptionPane.showMessageDialog(this, "error in saving");
            statusLabel.setText("Αλλαγές ΜΗ ΑΠΟΘΗΚΕΥΜΕΝΕΣ");
          }
        System.out.println("Record saved ");

        MyWindowEvent we = new MyWindowEvent(this, WindowEvent.WINDOW_CLOSED, true);
        for (WindowListener l : this.getWindowListeners())
          {
            l.windowClosed(we);
          }
        this.setVisible(false);
    }//GEN-LAST:event_saveAndBackButtonActionPerformed

    public void refershTable()
    {


        JTableBinding jj = SwingBindings.createJTableBinding(AutoBinding.UpdateStrategy.READ_WRITE, userRolesList, roleTable);
        ColumnBinding cc = jj.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${roleName}"));

        cc.setColumnName("Role Name");
        cc.setColumnClass(String.class);
        cc.setEditable(false);

        bindingGroup.addBinding(jj);
        jj.bind();
        jScrollPane1.setViewportView(roleTable);
        roleTable.getColumnModel().getColumn(0).setResizable(false);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[])
    {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try
          {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels())
              {
                if ("Nimbus".equals(info.getName()))
                  {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                  }
              }
          }
        catch (ClassNotFoundException ex)
          {
            java.util.logging.Logger.getLogger(ListUsersForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
          }
        catch (InstantiationException ex)
          {
            java.util.logging.Logger.getLogger(ListUsersForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
          }
        catch (IllegalAccessException ex)
          {
            java.util.logging.Logger.getLogger(ListUsersForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
          }
        catch (javax.swing.UnsupportedLookAndFeelException ex)
          {
            java.util.logging.Logger.getLogger(ListUsersForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
          }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                new ListRolesForm().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelButton;
    private javax.swing.JButton deleteRoleButton;
    private javax.swing.JButton editRoleButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JButton newRoleButton;
    private javax.swing.JTable roleTable;
    private javax.swing.JButton saveAndBackButton;
    private javax.swing.JButton saveButton;
    private javax.persistence.Query selectPermsByUserRoleQUERY;
    private java.util.List<RolePermission> selectPerrmsByUserRoleLIST;
    private javax.persistence.Query selectUserRolesQuery;
    private javax.swing.JLabel statusLabel;
    private java.util.List<UserRole> userRolesList;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
}
